package com.zhentao.filter;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.zhentao.constants.Constants;

import com.zhentao.user.domain.AppUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class FilterConfig implements GlobalFilter, Ordered {
    @Autowired
    private StringRedisTemplate redisTemplate;


    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 先获取 request \ response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getPath().toString();
        log.info("path {}", path);
        AppUser user=getUserInfo(request);
        if(antPathMatcher.match("/api/wx/**/auth/**",path)) {
            if (ObjectUtil.isEmpty(user)) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                // 终止过滤器
                return response.setComplete();
            }
        }
        // 放行
        return chain.filter(exchange);
    }

    private AppUser getUserInfo(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isBlank(token)){
            return null;
        }
        String json = redisTemplate.opsForValue().get("login:" + token);
        if(json==null){
            return null;
        }
        return JSON.parseObject(json, AppUser.class);
    }


    @Override
    public int getOrder() {
        return 2;
    }
}